<?php

namespace app\models;

use think\Model;

class Agent extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $updateTime = 'updated';


    /**
     * 资产变动变更记录
     * $type = 1 市代 2区代 2提现
     * @return void
     */
    public static function MoneyEdit($agentid, $type = 0, $money = 0, $info = '', $source = 0, $comeuser_id = 0)
    {
        if ($money != 0 && $agentid > 0) {
            $agent = (new Agent())->where('id', $agentid)->find();
            if (empty($agent)) {
                throw new \Exception("代理不存在，请重试", 100);
            }
            if ($money < 0 && $agent['money'] < $money) {
                throw new \Exception("资产不足，请重试", 100);
            }
            $res = (new Agent())->where(['id' => $agent['id'], 'money' => $agent['money']])->setInc('money', $money);
            if (!$res) {
                throw new \Exception("资产修改失败，请重试", 100);
            }
            $res2 = (new AgentLog())->save([
                'timeid' => time(),
                'user_id' => $agent['id'],
                'comeuser_id' => $comeuser_id,
                'befores' => $agent['money'],
                'money' => $money,
                'after' => ($agent['money'] + $money),
                'type' => $type,
                'info' => $info,
                'source' => $source
            ]);
            if (!$res2) {
                throw new \Exception("资产记录失败，请重试", 100);
            }
        }
    }
}
